package cn.seaboot.admin.security.login;

import cn.seaboot.admin.security.auth.SecurityAuthorityProvider;
import cn.seaboot.admin.user.bean.User;
import cn.seaboot.admin.user.dao.UserDao;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户鉴权信息查询接口
 *
 * @author Mr.css
 * @version 2020-05-08 0:02
 */
@Configuration
public class CustomUserDetailsService implements UserDetailsService {

    @Resource
    private UserDao userDao;

    @Resource
    private PasswordHelper passWordHelper;

    @Resource
    private SecurityAuthorityProvider securityAuthorityProvider;

    /**
     * 查询用户的信息
     *
     * @param userName 用户帐号
     * @return UserDetails 用户详细信息
     * @throws UsernameNotFoundException 未找到用户
     * @see UserDetailsService 相见Security配置
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userDao.selectFullByAccount(userName);
        if (user == null) {
            throw new UsernameNotFoundException("Username not found: " + userName);
        }

        // 获取用户的所有权限
        List<GrantedAuthority> grantedAuthorities = securityAuthorityProvider.queryGrantedAuthority(user);

        // 获取BCrypt加密的密码
        String bCryptPassword = passWordHelper.getBCryptPassword(user.getPassword(), user.getPasswordSalt());
        return new org.springframework.security.core.userdetails.User(user.getAccount(), bCryptPassword, grantedAuthorities);
    }
}
